package com.yexiao.cofe.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

@Component
public class SpringContextUtil implements BeanFactoryPostProcessor, ApplicationContextAware {
    private static ApplicationContext applicationContext;
    private static ConfigurableListableBeanFactory beanFactory;

    public SpringContextUtil() {
    }

    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        assertApplicationContext();
        return applicationContext;
    }

    public static <T> T getBean(Class<T> requiredType) {
        Assert.notNull(requiredType, "requiredType不能为null!");
        return getBeanFactory().getBean(requiredType);
    }

    private static void assertApplicationContext() {
        if (applicationContext == null) {
            throw new RuntimeException("applicationContext属性为null，请检查是否注入了SpringContextUtils!");
        }
    }

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        SpringContextUtil.beanFactory = beanFactory;
    }

    public static ListableBeanFactory getBeanFactory() {
        return (ListableBeanFactory)(null == beanFactory ? applicationContext : beanFactory);
    }
}
